﻿using System;
using System.ServiceModel;
using System.Windows;

namespace Songhay.Extensions
{
    using ServiceModel;

    /// <summary>
    /// Extension methods for <see cref="System.Windows.Application"/>.
    /// </summary>
    public static class ApplicationExtensions
    {
        /// <summary>
        /// Gets the service client binding.
        /// </summary>
        /// <param name="app">The app.</param>
        /// <remarks>
        /// For more details, see “Silverlight ServiceReferences.ClientConfig Alternatives”
        /// by Manish Dalal
        /// [http://weblogs.asp.net/manishdalal/archive/2009/02/23/silverlight-servicereferences-clientconfig-alternatives.aspx]
        /// </remarks>
        public static BasicHttpBinaryBinding GetServiceClientBinding(this Application app)
        {
            var mode = app.Host.Source.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase) ?
                BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None;
            var binding = new BasicHttpBinaryBinding(mode);

            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.MaxBufferSize = int.MaxValue;

            return binding;
        }

        /// <summary>
        /// Gets the service client endpoint address.
        /// </summary>
        /// <param name="app">The app.</param>
        /// <param name="relativeUri">The relative URI.</param>
        public static EndpointAddress GetServiceClientEndpointAddress(this Application app, string relativeUri)
        {
            var uri = new Uri(app.Host.Source, relativeUri);
            return new EndpointAddress(uri);
        }
    }
}
